package com.core.sdk.core;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.core.sdk.R;
import com.core.sdk.event.NetWorkEvent;
import com.core.sdk.ui.dialog.LightNetWorkSetDialog;
import com.core.sdk.ui.dialog.LightProgressDialog;
import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockFragmentActivity;
import com.google.inject.Inject;

/**
 * description:RoboFragmentActivity
 * 继承RoboSherlockFragmentActivity之后，不但可以使用roboguice还可以使用ActionbarSherlock
 * @author liguo
 *
 */
public abstract class BaseActivity extends RoboSherlockFragmentActivity implements MessageHandListener, MessageSendListener, OnViewSizeConfirmed, OnActionBarItemSelectedListener {

	protected String tag = this.getClass().getSimpleName();
	private volatile BaseApplication app = null;
	private final Location from = new Location(this.getClass().getName());
	public final String DATA_SERIALIZABLE = "DATA_SERIALIZABLE";

	protected int activityWidth = 0;
	protected int activityHeight = 0;
	
	@Inject
	ActivityManager activityManager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initGlobalView();
		if(validFullScreen()){
			enableFullScreen();
		}
		setContentView(mGlobalView);
		app = (BaseApplication) getApplication();
		app.registerTtListener(this);

		initGoBack();
		calcViewSize(mGlobalView, this);
		if (actionBarView != null) {
			calcViewSize(actionBarView, new OnViewSizeConfirmed() {
				@Override
				public void onViewSizeConfirmed(View v, int width, int height) {
					actionBarHeight = height;
				}
			});
		}
	}
	
	protected final ViewGroup getGlobalView(){
		return this.mGlobalView;
	}

	/** 计算View的宽高 */
	protected final void calcViewSize(final View v, final OnViewSizeConfirmed listener) {
		ViewTreeObserver vto = v.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				v.getViewTreeObserver().removeGlobalOnLayoutListener(this);
				listener.onViewSizeConfirmed(v, v.getWidth(), v.getHeight());
			}
		});
	}

	/** 获取activity的宽高 */
	@Override
	public void onViewSizeConfirmed(View v, int width, int height) {
		activityWidth = v.getWidth();
		activityHeight = v.getHeight();
	}

	/** 初始返回事件，并提供onGoBack()方法供子类实现具体的逻辑 */
	private void initGoBack() {
		if (getGoBackResourceId() <= 0)
			return;
		View goBackView = findViewById(getGoBackResourceId());
		goBackView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onGoBack();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		app.unRegisterTtListener(this);
	}

	public final void sendEvent(BaseEvent evt) {
		try {
			if (evt.getFrom() == null) {
				evt.setFrom(getLocation());
			}
			app.sendEvent(evt);
		} catch (BaseException e) {
			e.printStackTrace();
		}
	}

	public final void sendMessage(Message msg) {
		BaseMessage tmsg = new BaseMessage(from, msg);
		app.sendMessage(tmsg);
	}

	public final void sendEmptyMessage(int what) {
		Message msg = Message.obtain();
		msg.what = what;
		BaseMessage tmsg = new BaseMessage(from, msg);
		app.sendMessage(tmsg);
	}

	public final void sendMessageDelayed(Message msg, long delayMillis) {
		BaseMessage tmsg = new BaseMessage(from, msg);
		app.sendMessageDelayed(tmsg, delayMillis);
	}

	public final void sendEmptyMessageDelayed(int what, long delayMillis) {
		Message msg = Message.obtain();
		msg.what = what;
		BaseMessage tmsg = new BaseMessage(from, msg);
		app.sendMessageDelayed(tmsg, delayMillis);
	}
	
	public final void removeMessage(int what){
		app.removeMessage(what);
	}

	/**检测是否在UI线程中运行*/
	protected final void checkRunOnUI() {
		app.checkRunOnUI();
	}

	/**检测是否在二线程或主线程中运行*/
	protected final void checkRunOnMain() {
		app.checkRunOnMain();
	}

	protected final Location getLocation() {
		return new Location(this.getClass().getName());
	}

	public static final Location findLocation(Class<?> cls) {
		return new Location(cls.getName());
	}

	/** 提交到UI线程中处理 */
	protected final void postRunOnUi(UITask task) {
		app.postRunOnUi(task);
	}


	/** 处理Event，是在二线程中 */
	@Override
	public void executeEvent(BaseEvent evt) {
		if (evt instanceof NetWorkEvent) {
			Bundle bd = new Bundle();
			bd.putSerializable("obj", evt);
			postRunOnUi(new UITask(this, bd) {
				@Override
				public void run() {
					NetWorkEvent event = (NetWorkEvent) getExtra().getSerializable("obj");
					onNetworkStateChanged(event);
				}
			});
		}
	}

	/** 处理Message，是在UI线程中 */
	@Override
	public void executeMessage(Message msg) {

	}

	/**当网络状态发生改变时的处理*/
	protected void onNetworkStateChanged(NetWorkEvent evt) {
		if (evt.isAvailable()) {
			LogUtil.d(tag, "当前网络可用,类型:" + evt.getNetWorkType().name());
		} else {
			List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1) ;
		    if(runningTaskInfos == null || runningTaskInfos.size() == 0)
		    	return ;
		    //必须判断当前Activity是否在栈顶，如果是才弹出网络提示框
		    String topActivityName = (runningTaskInfos.get(0).topActivity).getClassName();		
		    if(this.getClass().getName().equals(topActivityName)){
		    	showNetWorkDialog("网络已断开","当前网络不可用,是否现在就设置?");
		    }
		}
	}

	/** 代替findViewById */
	@SuppressWarnings("unchecked")
	protected <V extends View> V find(int id) {
		return (V) this.findViewById(id);
	}

	public BaseApplication getBaseApplication() {
		return this.app;
	}

	/**本Activity对应的xml文件*/
	protected abstract int getContentView();

	// ==============================================
	/** 返回的ResID */
	protected int getGoBackResourceId() {
		View v = findViewById(R.id.action_bar_left_layout);
		return v == null ? -1 : v.getId();
	}

	/** 当点击返回按钮时调用 */
	protected void onGoBack() {
		this.finish();
	}
	
	/** 是否启用合屏 */
	protected boolean validFullScreen(){
		return false;
	}
	
	/** 启用全屏 */
	private void enableFullScreen(){
		//设置无标题  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        //设置全屏  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);  
	}

	// ====================actionbar->begin=========================

	/** Actionbar创建的时候,如果需要则返回Actionbar */
	protected ActionBarMenu onActionBarCreate() {
		return null;
	}

	protected ViewGroup mGlobalView = null;
	ActionBarMenu mActionBar = null;
	private int actionBarHeight = 0;
	View actionBarView = null;

	/** 初始化合局View
	 *  主要是判断是否有自定义的ActionBar，如果有则创建一个LinearLayout，然后分别加Actionbar，及contentView
	 *  
	 *  */
	private void initGlobalView() {
		ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this).inflate(getContentView(), null);
		mActionBar = onActionBarCreate();
		if (mActionBar != null) {
			mGlobalView = getLinearLayout();
			actionBarView = inflateActionBarView();
			actionBarHeight = actionBarView.getHeight();
			mActionBar.setViewAndListener(actionBarView, this);
			mGlobalView.addView(actionBarView);
			mGlobalView.addView(viewGroup);
		} else {
			mGlobalView = viewGroup;
		}
	}

	/**合建一个全新的垂直的LinearLayout*/
	private LinearLayout getLinearLayout() {
		LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.VERTICAL);
		int width = LinearLayout.LayoutParams.FILL_PARENT;
		int height = LinearLayout.LayoutParams.FILL_PARENT;
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
		ll.setLayoutParams(lp);
		return ll;
	}

	/** 获得ActionBarView */
	private View inflateActionBarView() {
		View v = LayoutInflater.from(this).inflate(R.layout.layout_actionbar, null);
		return v;
	}

	/** ActionBar中的View的点击事件 */
	@Override
	public void onActionBarClick(View v) {

	}
	
	/** 获得Actionbar的高度 */
	protected final int getActionBarHeight() {
		return this.actionBarHeight;
	}
	
	/**返回 ActionBar实例*/
	protected final ActionBarMenu getActionBarMenu(){
		return this.mActionBar;
	}	
	
	//=================进度条==============
	AlertDialog progressDialog = null;
	/** 弹出对证框 */
	protected final AlertDialog showProgressDialog(String message){
		if(progressDialog != null){
			closeProgressDialog();
		}	
		progressDialog = LightProgressDialog.create(this, message);
		progressDialog.show();
		return progressDialog;
	}
	/**关闭对话框*/
	protected final void closeProgressDialog(){
		if(progressDialog == null)
			return ;
		progressDialog.dismiss();
		progressDialog = null;
	}
	
	//==================网络设置dialog=================
	AlertDialog networkDialog = null;
	/**显示网络对话框架*/
	protected final AlertDialog showNetWorkDialog(String title,String message){
		if(networkDialog != null)
			closeNetWorkDialog();
		networkDialog = LightNetWorkSetDialog.create(this, title, message);
		networkDialog.show();
		return networkDialog;
	}
	/** 关闭网络对话框 */
	protected final void closeNetWorkDialog(){
		if(networkDialog == null)
			return ;
		networkDialog.dismiss();
		networkDialog  = null;
	}
	//=====================未处理事件队列======================
	//protected volatile LinkedBlockingQueue<BaseEvent> events = new LinkedBlockingQueue<BaseEvent>();
}
